<template>
  <el-dialog
    title="试卷下载"
    :visible.sync="dialogVisible"
    width="600px"
    @close="handleClose"
    @closed="handleClosed"
  >
    <div>
      <el-form ref="form" :model="form" label-width="130px" label-position="left">
        <el-form-item label="题型位置：">
          <el-radio-group v-model="form.topicTypePosition">
            <el-radio :label="1">题前</el-radio>
            <el-radio :label="0">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分值位置：">
          <el-radio-group v-model="form.scorePosition">
            <el-radio :label="1">题后</el-radio>
            <el-radio :label="0">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="答案位置：">
          <el-radio-group v-model="form.answerPosition">
            <el-radio :label="1">题后</el-radio>
            <el-radio :label="2">卷尾</el-radio>
            <el-radio :label="0">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="解析位置：">
          <el-radio-group v-model="form.resolvePosition">
            <el-radio :label="1">题后</el-radio>
            <el-radio :label="2">卷尾</el-radio>
            <el-radio :label="0">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="作答区域：">
          <el-radio-group v-model="form.answerAreaFlag">
            <el-radio :label="1">添加</el-radio>
            <el-radio :label="0">不添加</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="导出格式：">
          <el-radio-group v-model="form.exportFormat">
            <el-radio label="docx">DOCX</el-radio>
            <el-radio label="doc">DOC</el-radio>
            <el-radio label="pdf">PDF</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="handleClose">取 消</el-button>
    <el-button type="primary" @click="handleConfirm">下 载</el-button>
  </span>
  </el-dialog>
</template>

<script>
import { exportExamPaperApi } from '@/api/ExaminationModule'
import { formatDate } from '@/utils'
import { exportinput } from '@/api/questions/statistics'
import { Loading, Message, MessageBox } from 'element-ui'
import errorCode from "@/utils/errorCode";
import store from '@/store'
import { isRelogin } from '@/utils/request'
export default {
  name: 'downloadPaper',
  data() {
    return {
      dialogVisible: false,
      needReset: false,
      paperId: void 0,
      form: {
        topicTypePosition: 0,
        scorePosition: 1,
        answerPosition: 1,
        resolvePosition: 1,
        answerAreaFlag: 0,
        exportFormat: 'docx'
      },
      //试卷类型文字键值对
      operationTypeText:{
        1:'考核',
        3:'练习',
        6:'课后作业'
      },
      examType:void 0,
      paperTitle:void 0,
    }
  },
  methods: {
    handleShow(id,examType,paperTitle) {
      this.paperId = id
      this.examType = examType
      this.paperTitle = paperTitle
      this.dialogVisible = true
    },
    handleClose() {
      this.needReset = true;
      this.dialogVisible = false;
    },
    handleClosed() {
      if (this.needReset) {
        this.resetForm();
        this.needReset = false;
      }
    },
    resetForm() {
      this.form = {
        topicTypePosition: 0,
        scorePosition: 1,
        answerPosition: 1,
        resolvePosition: 1,
        answerAreaFlag: 0,
        exportFormat: 'docx'
      };
    },
    async handleConfirm() {
      let arr=this.paperTitle.split('/')
      let name = arr.join('-')
     let downloadLoadingInstance = Loading.service({
        text: "正在下载数据，请稍候",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let data = { ...this.form, examId: this.paperId }
      exportExamPaperApi(data).then(async(res) => {
        // 检查返回的Blob是否包含错误信息
        const contentType = res.type;
        // 如果是JSON类型，说明可能返回了错误信息
        if (contentType.includes('application/json') ||
          contentType.includes('text/plain')) {
          // 将Blob转换为文本查看错误信息
          const resText = await res.text();
          const rspObj = JSON.parse(resText);
          const code = rspObj.code;
          if (code === 401) {
            if (!isRelogin.show) {
              isRelogin.show = true;
              MessageBox.confirm(
                "登录状态已过期，或已在其他设备登录，请重新登录",
                "系统提示",
                {
                  confirmButtonText: "重新登录",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              )
                .then(() => {
                  isRelogin.show = false;
                  store.dispatch("LogOut").then(() => {
                    location.href = `${process.env.VUE_APP_BASE_PATH}index`;
                  });
                })
                .catch(() => {
                  isRelogin.show = false;
                });
            }
          }else{
            const errMsg =
              errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
            Message.info({ message: errMsg, showClose: true });
          }
          return;
        }
          // 1. 设置正确的Blob类型
          const mimeType = this.getMimeType(data.exportFormat);

          const blob = new Blob([res], { type: mimeType });

          // 3. 设置正确的文件名
          let fileName = `${this.operationTypeText[this.examType]}-${name}.${data.exportFormat}`;
          console.log('文件名:', fileName);

          // 4. 下载文件
          this.downloadFile(blob, fileName);
      }).catch(error => {
        console.error('导出失败:', error);
        this.$message.error('导出失败：' + (error.message || '网络错误'));
      }).finally(() => {
        downloadLoadingInstance.close();
      });
      this.dialogVisible = false
    },
    // 根据文件格式获取MIME类型
    getMimeType(format) {
      const typeMap = {
        'pdf': 'application/pdf',
        'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'xls': 'application/vnd.ms-excel',
        'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'doc': 'application/msword',
        'txt': 'text/plain',
        'csv': 'text/csv'
      };
      return typeMap[format] || 'application/octet-stream';
    },

    // 下载文件方法
    downloadFile(blob, fileName) {
      if ('download' in document.createElement('a')) {
        const link = document.createElement('a');
        link.download = fileName;
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        document.body.appendChild(link);
        link.click();
        // 延迟释放URL，确保下载完成
        setTimeout(() => {
          URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        }, 100);
      } else {
        // IE兼容
        navigator.msSaveBlob(blob, fileName);
      }
    },

    // 日期格式化方法
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}${month}${day}_${hours}${minutes}`;
    }
  }
}

</script>

<style scoped lang="scss">

</style>
